package com.huatek.framework.security;

import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.huatek.framework.entity.FwAccount;
import com.huatek.framework.util.CommonUtil;


public class ClientInformationImpl implements  ClientInformation{

	private static final String SYSTEM_CODE = "SYSTEM_CODE";
	public static final String CREATE_GROUP = "createGroup";
	public static final String MENU_ID = "menuId";
	public static final String LOGIN_ACCOUNT = "LoginAccount";
	public static final String ACTION_URL = "actionURL";
	public static final String DEFAULT_METHOD = "query";
	public static final String ACTION_METHOD = "actionMethod";
	public ClientInfoBean collectClientInfo(HttpServletRequest request) {
		ClientInfoBean frameBean = new ClientInfoBean();
		String actionName = getActionName(request);
		frameBean.setHostIp(request.getRemoteHost());
		frameBean.setHostPort(request.getRemotePort());
		if(CommonUtil.isNotZeroLengthTrimString(request.getParameter(MENU_ID))){
			frameBean.setMenuId(Long.valueOf(request.getParameter(MENU_ID)));
			request.getSession().setAttribute(MENU_ID, frameBean.getMenuId());
		}else{
			if(request.getSession().getAttribute(MENU_ID)!=null){
				frameBean.setMenuId((Long)request.getSession().getAttribute(MENU_ID));
			}
		}
		if(CommonUtil.isNotZeroLengthTrimString(request.getParameter(SYSTEM_CODE))){
			frameBean.setSystemCode(request.getParameter(SYSTEM_CODE));
		}
		frameBean.setContextPath(request.getContextPath());
		frameBean.setServerPort(request.getServerPort());
		frameBean.setServerHost(request.getServerName());
		frameBean.setActionURL(actionName);
		frameBean.setActualActionPath(actionName);
		String actionMethod = request.getParameter(ACTION_METHOD);
		if (actionMethod == null) {
			actionMethod = DEFAULT_METHOD;
		}
		frameBean.setRequestMethod(request.getMethod());
		frameBean.setActionMethod(actionMethod);
		frameBean.setAccessCalendar(Calendar.getInstance());
		HttpSession session = request.getSession();
		FwAccount accountBean = (FwAccount) session.getAttribute(LOGIN_ACCOUNT);
		frameBean.setOperator(accountBean);
		frameBean.setRequest(request);
		return frameBean;
	}
	protected static String getActionName(HttpServletRequest request) {
		String actionName = request.getParameter(ACTION_URL);
		if (CommonUtil.isZeroLengthTrimString(actionName)) {
			String requestURL = request.getRequestURI();
			if (requestURL != null) {
				actionName = requestURL
						.substring(requestURL.lastIndexOf("/") + 1);
				if (actionName.indexOf("?") > 0) {
					actionName = actionName.substring(0, actionName
							.indexOf("?"));
				}
			}
		}
		return actionName;
	}

}
